package bill;

import enums.BillOutStatus;
import enums.BillStatus;
import models.BaseModel;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import order.Order;
import order.OrderItem;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;

import javax.persistence.*;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/9/8.
 */
@Entity
@Table(name = "bill")
public class Bill extends BaseModel {

    /**
     * 关联商户
     */
    @JoinColumn(name = "merchant_id")
    @ManyToOne
    public Merchant merchant;

    /**
     * 关联订单明细
     */
    @JoinColumn(name = "order_item")
    @ManyToOne
    public OrderItem orderItem;

    /**
     * 金额
     */
    @Column(name = "amount")
    public Double amount;


    /**
     *  账务状态 ：入账，出账
     */
    @Column(name = "status")
    @Enumerated(EnumType.STRING)
    public BillStatus status;

    /**
     * 提现状态
     */
    @Column(name = "out_status")
    @Enumerated(EnumType.STRING)
    public BillOutStatus outStatus;

    /**
     * 逻辑删除,0:未删除，1:已删除
     */
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;

    public static  Bill  getBillByOrderItem(OrderItem orderItem){
        return Bill.find(" orderItem.id = ? and deleted = ?",orderItem.id,DeletedStatus.UN_DELETED).first();
    }


    /**
     * 查询 订单 总金额，冻结金额，课题提现金额
     */
    public static List<Map<String,Object>> loadAmount(long merchantId, BillOutStatus outStatus){
        String sqlSelect="select IFNULL(sum(amount),0) as sumAmount from bill where 1=1 and merchant_id="+merchantId;
        sqlSelect += " and status = 'IN_AMOUNT' ";
        if(outStatus != null){
            // 冻结状态
            if(outStatus == BillOutStatus.FROZEN){
                sqlSelect += " and out_status ='"+BillOutStatus.FROZEN+"'";
                // 正常状态
            }else if(outStatus == BillOutStatus.NORMAL){
                sqlSelect += " and out_status ='"+BillOutStatus.NORMAL+"'";
            }

        }
        Query query= Order.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }

    public static  List<Bill>  getBillListByFrozen(Merchant merchant,BillOutStatus billOutStatus,BillStatus billStatus){
        return Bill.find(" merchant.id = ? and deleted = ? and outStatus = ? and status = ?",merchant.id,DeletedStatus.UN_DELETED,billOutStatus,billStatus).fetch();
    }

}
